package com.easy.framework.database.handle;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.easy.framework.common.constant.I18NConstants;
import com.easy.framework.common.utils.I18NUtils;
import com.easy.framework.database.enums.DelFlag;
import com.easy.framework.security.model.LoginUser;
import com.easy.framework.security.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;

/**
 * 数据填充
 * 需要再字段增加 @TableField(fill = FieldFill.INSERT) 注解
 *
 * @author Yang Huijing
 */
@Component
public class DataFillHandle implements MetaObjectHandler {
    private static final String CREATED_BY = "createdBy";
    private static final String CREATED_AT = "createdAt";
    private static final String UPDATED_BY = "updatedBy";
    private static final String UPDATED_AT = "updatedAt";
    private static final String DEL_FLAG = "delFlag";

    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getUserId();
        this.strictInsertFill(metaObject, CREATED_BY, Long.class, userId);
        this.strictInsertFill(metaObject, CREATED_AT, Date.class, new Date());
        this.strictInsertFill(metaObject, UPDATED_BY, Long.class, userId);
        this.strictInsertFill(metaObject, UPDATED_AT, Date.class, new Date());
        this.strictInsertFill(metaObject, DEL_FLAG, Integer.class, DelFlag.normal.getValue());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, UPDATED_BY, Long.class, getUserId());
        this.strictUpdateFill(metaObject, UPDATED_AT, Date.class, new Date());
    }


    public Long getUserId() {
        LoginUser user = SecurityUtils.getUser();
        if (user == null) {
            return 0L;
        }
        return user.getUserId();
    }

}
